package fr.utbm.tx52.stamp.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import fr.utbm.tx52.stamp.R;
import fr.utbm.tx52.stamp.adapter.ImageAdapter;
import fr.utbm.tx52.stamp.logic.Constant;
import fr.utbm.tx52.stamp.logic.Contact;
import fr.utbm.tx52.stamp.logic.algorithm.SortAlgorithms;
import fr.utbm.tx52.stamp.logic.utils.FileUtil;
import fr.utbm.tx52.stamp.logic.utils.LocalizationUtil;
import fr.utbm.tx52.stamp.ui.actionprovider.ContactBadge;
import fr.utbm.tx52.stamp.ui.fragment.ZoomImageView;
import java.io.File;
import java.io.IOException;

/**
 * Class which is used to see an image in full screen with the possibilty to see
 * comment and listen audio comment
 *
 * @author GREA Antoine
 * @author TISSERAND Geoffrey
 */
public class Viewer extends Activity
{

	public static final String INDEX_KEY = "index";
	public static final String PATH_KEY = "path";
	public static final String FROM_KEY = "from";
	public static final String COMMENT_KEY = "coment";
	public static final String TITLE_KEY = "title";
	public static final String AUDIO_COMMENT_KEY = "audio";
	public static Viewer instance;
	private String comment;
	private String title;
	private File audio;
	private MenuItem senderItem;
	public static SortAlgorithms sort;
	private MenuItem locate;

	public enum PlayState
	{

		PLAYING,
		PAUSED,
		REPLAY;

		public PlayState next()
		{
			switch (this)
			{
				case PAUSED:
				case REPLAY:
					return PLAYING;
			}
			return PlayState.values()[ordinal() + 1];
		}
	}
	private PlayState recordState = PlayState.PAUSED;
	/**
	 * Lecteur audio
	 */
	private MediaPlayer mediaPlayer = new MediaPlayer();
	public ImageAdapter imageAdapter = new ImageAdapter(this, ImageAdapter.Listener.SELECT);
	private int position;

	public void select(int position)
	{
		this.position = position;
		file = imageAdapter.getFile(position);
		if (!"".equals(imageAdapter.getSender(position)))
		{
			sender = Contact.getContactsByPhone(this, imageAdapter.getSender(position));
		}
		comment = imageAdapter.getComment(position);
		title = imageAdapter.getFile(position).getName();
		audio = imageAdapter.getAudioComment(position);
		draw();
	}
	private File file;
	private Contact sender;

	public File getFile()
	{
		return file;
	}

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		instance = this;
		getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
		setContentView(R.layout.viewer);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_dark_fade));
		sort = new SortAlgorithms(imageAdapter.getFiles());
		position = getIntent().getIntExtra(INDEX_KEY, -1);
		if (position == -1)
		{
			file = new File(getIntent().getStringExtra(PATH_KEY));
			sender = Contact.getContactsByPhone(this, getIntent().getStringExtra(FROM_KEY));
			comment = getIntent().getStringExtra(COMMENT_KEY);
			title = getIntent().getStringExtra(TITLE_KEY);
			audio = new File(getIntent().getStringExtra(AUDIO_COMMENT_KEY));

		}
		else
		{
			file = imageAdapter.getFile(position);
			if (!"".equals(imageAdapter.getSender(position)))
			{
				sender = Contact.getContactsByPhone(this, imageAdapter.getSender(position));
			}
			comment = imageAdapter.getComment(position);
			title = imageAdapter.getFile(position).getName();
			audio = imageAdapter.getAudioComment(position);
		}

		draw();
	}

	private void draw()
	{
		ZoomImageView imageView = new ZoomImageView(this);
                imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
		imageView.setImageBitmap(FileUtil.loadBitmap(getContentResolver(), Uri.fromFile(file)));
                imageView.correctPositionning();
                final RelativeLayout imageLayout = (RelativeLayout) findViewById(R.id.image_layout);
                imageLayout.removeAllViews();
                imageLayout.addView(imageView);
		if (senderItem != null)
		{
			senderItem.setActionProvider(new ContactBadge(this, (sender == null) ? Uri.EMPTY : this.sender.getUri()));
			senderItem.setVisible((sender != null));
		}
		getActionBar().hide();
		final RelativeLayout overlay = (RelativeLayout) findViewById(R.id.viewer_overlay);
		overlay.setVisibility(View.INVISIBLE);

		final ImageView audioComment = (ImageView) overlay.findViewById(R.id.viewer_overlay_audio_comment);
		audioComment.setVisibility((new File(FileUtil.getSoundPath(file.getAbsolutePath())).exists()) ? View.VISIBLE : View.INVISIBLE);
		try
		{
			mediaPlayer.setDataSource(FileUtil.getSoundPath(file.getAbsolutePath()));
			mediaPlayer.prepare();
			mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
			{

				public void onCompletion(MediaPlayer mp)
				{
					audioComment.setImageResource(R.drawable.ic_overlay_dark_replay);
					recordState = PlayState.REPLAY;
				}
			});
		}
		catch (IOException ex)
		{
			Log.e(Share.class.getSimpleName(), "", ex);
		}
		catch (IllegalArgumentException ex)
		{
			Log.e(Share.class.getSimpleName(), "", ex);
		}
		catch (SecurityException ex)
		{
			Log.e(Share.class.getSimpleName(), "", ex);
		}
		catch (IllegalStateException ex)
		{
			Log.e(Share.class.getSimpleName(), "", ex);
		}



		audioComment.setOnClickListener(new View.OnClickListener()
		{

			public void onClick(final View v)
			{
				switch (recordState)
				{
					case PLAYING:
						mediaPlayer.stop();
						break;
					case PAUSED:
					case REPLAY:
						audioComment.setImageResource(R.drawable.ic_overlay_dark_pause);
						mediaPlayer.start();
						break;
				}
			}
		});


		TextView commentOverlay = ((TextView) overlay.findViewById(R.id.viewer_overlay_comment));
		commentOverlay.setText(this.comment);
		commentOverlay.setTextAppearance(this, android.R.style.TextAppearance_Holo_Medium);
		commentOverlay.setVisibility(((this.comment == null || "".equals(this.comment)) ? View.INVISIBLE : View.VISIBLE));
		setTitle(file.getName());


		overlay.setOnClickListener(new View.OnClickListener()
		{

			public void onClick(View v)
			{
				getActionBar().hide();
				overlay.setVisibility(View.INVISIBLE);
			}
		});


		ImageView next = (ImageView) findViewById(R.id.viewer_overlay_next);
		next.setVisibility((position == imageAdapter.getCount() - 1) ? View.INVISIBLE : View.VISIBLE);

		next.setOnClickListener(new View.OnClickListener()
		{

			public void onClick(View v)
			{
				select(++position);
			}
		});

		ImageView previous = (ImageView) findViewById(R.id.viewer_overlay_previous);
		previous.setVisibility((position == 0) ? View.INVISIBLE : View.VISIBLE);

		previous.setOnClickListener(new View.OnClickListener()
		{

			public void onClick(View v)
			{
				select(--position);
			}
		});

		if (locate != null)
		{
			locate.setVisible(LocalizationUtil.coordinateExists(file));
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.viewer, menu);

		locate = menu.findItem(R.id.viewer_locate);
		locate.setVisible(LocalizationUtil.coordinateExists(file));
		locate.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener()
		{

			public boolean onMenuItemClick(MenuItem item)
			{
				final Intent intent = new Intent(Viewer.this, Maps.class);
				intent.putExtra(Constant.BUNDLE_KEY_PICTURE_LATITUDE, LocalizationUtil.getLatitude(getFile()));
				intent.putExtra(Constant.BUNDLE_KEY_PICTURE_LONGITUDE, LocalizationUtil.getLongitude(getFile()));
				startActivity(intent);
				return true;
			}
		});

		senderItem = menu.findItem(R.id.viewer_sender);
		senderItem.setActionProvider(new ContactBadge(this, (sender == null) ? Uri.EMPTY : this.sender.getUri()));

		// Calling super after populating the menu is necessary here to ensure
		// that the
		// action bar helpers have a chance to handle this event.
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case android.R.id.home:
				if (!Main.launched)
				{
					final Intent intent = new Intent(this, Main.class);
					startActivity(intent);
				}
				finish();
				return true;
		}
		return false;
	}
        
        public void setOverlayVisible(){
            getActionBar().show();
            ((RelativeLayout) findViewById(R.id.viewer_overlay)).setVisibility(View.VISIBLE);
        }
}